import { ConfigProvider, Watermark } from 'antd';
import type { PropsWithChildren } from 'react';
import { useEffect } from 'react';

import { globalConfig } from '@/config';
import { info } from '@/constants/app';
import { antdLocales } from '@/locales/antd';
import { localStg } from '@/utils/storage';

import { useLang } from '../lang';
import { useTheme } from '../theme';
import { getAntdTheme, setupThemeVarsToHtml, toggleAuxiliaryColorModes, toggleGrayscaleMode } from '../theme/shared';
import { useThemeColors, useThemeSettings } from '../theme/themeHook';

const useAntdTheme = () => {
  const themeSettings = useThemeSettings();
  const colors = useThemeColors();
  const { darkMode } = useTheme();
  const antdTheme = getAntdTheme(colors, darkMode, themeSettings.tokens);

  useEffect(() => {
    setupThemeVarsToHtml(colors, themeSettings.tokens, themeSettings.recommendColor);
    localStg.set('themeColor', colors.primary);

    toggleAuxiliaryColorModes(themeSettings.colourWeakness);
    toggleGrayscaleMode(themeSettings.grayscale);
  }, [colors, themeSettings]);

  console.info(`%c${info}`, `color: ${colors.primary}`);

  return { antdTheme, watermarkText: themeSettings.watermark.text, watermarkVisible: themeSettings.watermark.visible };
};

const AntdProvider = ({ children }: PropsWithChildren) => {
  const { locale } = useLang();
  const { antdTheme, watermarkText, watermarkVisible } = useAntdTheme();
  return (
    <ConfigProvider
      button={{ classNames: { icon: 'align-1px  text-icon' } }}
      card={{ styles: { body: { flex: 1, overflow: 'hidden', padding: '12px 16px ' } } }}
      locale={antdLocales[locale]}
      theme={antdTheme}>
      <Watermark
        className="h-full"
        content={watermarkVisible ? watermarkText || globalConfig.watermarkText : ''}
        {...globalConfig.watermarkConfig}>
        {children}
      </Watermark>
    </ConfigProvider>
  );
};
export default AntdProvider;
